package games.ninJumpDx.ui.sound
{
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	
	import games.ninJumpDx.data.GameData;

	public class Mp3Player
	{
		private var m_sound:Sound;
		private var m_channel:SoundChannel;

		private var m_url:String;
		private var m_list:Array;
		private var m_loop:Boolean;
		private var m_index:int;
		
		public function Mp3Player()
		{
		
		}
	
		
		public function playList(list:Array,loop:Boolean = false):void
		{
			m_list = list;
			m_loop = loop;
			m_index = 0;
			play(m_list[m_index]);
		}
		
		public function setVolume(n:Number):void
		{
			var trans:SoundTransform = new SoundTransform(n);
			m_channel.soundTransform = trans;
		}
		
		// 播放指定路径音乐
		private function play(url:String):void
		{
			m_url = url;
			if(m_channel) m_channel.stop();
			m_sound = new Sound();
			m_sound.addEventListener(Event.COMPLETE,completeHandler);
			m_sound.load(new URLRequest(m_url));
			
		}
		
		private function completeHandler(e:Event):void
		{
			m_channel = m_sound.play();
			m_channel.addEventListener(Event.SOUND_COMPLETE,onPlayEnd);
			setVolume(GameData.instance.music?.2:0);
		}
		
		private function onPlayEnd(e:Event):void
		{
			if(m_index < m_list.length - 1)
			{
				m_index ++;
			}else
			{
				if(m_loop)
				{
					m_index = 0;
				}
			}
			play(m_list[m_index]);
			
		}
	}
}